package system_sms_service

import (
	"encoding/json"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	gonanoid "github.com/matoous/go-nanoid"
)

func (cls *Sms) LogTimeTo(ctx context.Context, telephone string, templateCode string, templateParams map[string]string, sendTime int64) errors.Error {
	if "" == telephone || "" == templateCode {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.LTT_TO.111735 异常的传入参数，telephone is %q, templateCode is %q", telephone, templateCode)

		return errors.ErrorServerInternalError("ISS_MS.S_MS.LTT_TO.131744", "异常的传入参数")
	}

	var log = new(model.SystemSmsLog)

	if nil == templateParams {
		templateParams = make(map[string]string)
	}

	bs, err := json.Marshal(templateParams)
	if nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.LTT_TO.301925 序列化模板参数失败，错误信息为 %q", err.Error())

		return errors.ErrorServerInternalError("ISS_MS.S_MS.LTT_TO.321930", "序列化模板参数失败")
	}

	log.Id = gonanoid.MustID(64)
	log.SendType = pointer.New(model.SystemSmsLogSendTypeTime)
	log.SendTime = pointer.New(sendTime)
	log.Telephone = pointer.New(telephone)
	log.TemplateCode = pointer.New(templateCode)
	log.TemplateParams = pointer.New(string(bs))
	log.Status = pointer.New(model.SystemSmsLogStatusPending)

	if err := cls.smsLog.SaveSystemSmsLog(ctx, log); nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_MS.S_MS.LTT_TO.442006", "保存短信日志失败"))
	}

	return nil
}
